package org.algorithm.wE1.字符串;

import java.util.Arrays;

/**
 * @date 2022-04-14 星期四 00:00
 * 输入：s1 = "ab" s2 = "eidbaooo"
 * 输出：true
 * 解释：s2 包含 s1 的排列之一 ("ba").
 * 示例 2：
 *
 * 输入：s1= "ab" s2 = "eidboaoo"
 * 输出：false
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/permutation-in-string
 */
public class 字符串的排列2 {
    public static void main(String[] args) {
        String s1 = "ab" ;
        String s2 = "eidbaooo";
        System.out.println("checkInclusion(s1,s2) = " + checkInclusion(s1, s2));
    }
    public static boolean checkInclusion(String s1, String s2) {
        int ln1 = s1.length();
        int ln2 = s2.length();
        if(ln1>ln2){
            return false;
        }
        int[] arr1 = new int[26];
        int[] arr2 = new int[26];
        // arr1{    1,            1,       .....,0}
        //index 'a'-'a'=0    'b'-'b'=1
        //arr2{'e','i;}
        for (int i = 0; i <ln1 ; ++i) {
            //index(a) = s.charAt(i) - 'a' = 0
            //index(b) = s.charAt(i) - 'a' = 1
            //.......
            //index(z) = s.charAt(i) - 'a' = 25
            ++arr1[s1.charAt(i)-'a'];
            ++arr2[s2.charAt(i)-'a'];
        }
        if(Arrays.equals(arr1,arr2)){
            return true;
        }
        //创建 ln1 长度的窗口 并滑动起来 比较 arr1和arr2
        for (int right = ln1; right <ln2 ; ++right) {
            arr2[s2.charAt(right)-'a']++;
            int left = right - ln1;
            arr2[s2.charAt(left)-'a']--;
            if(Arrays.equals(arr1,arr2)){
                return true;
            }
        }
        return false;
    }
}
